package cn.edu.hbvtc.qms.web.struts.action;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import cn.edu.hbvtc.qms.domain.Category;
import cn.edu.hbvtc.qms.domain.ClazzArrangement;
import cn.edu.hbvtc.qms.domain.Course;
import cn.edu.hbvtc.qms.domain.Criteria;
import cn.edu.hbvtc.qms.domain.Department;
import cn.edu.hbvtc.qms.domain.EvalPeriod;
import cn.edu.hbvtc.qms.domain.Evaluation;
import cn.edu.hbvtc.qms.domain.Item;
import cn.edu.hbvtc.qms.domain.Student;
import cn.edu.hbvtc.qms.domain.Teacher;
import cn.edu.hbvtc.qms.domain.User;
import cn.edu.hbvtc.qms.service.IEvaluationService;
import cn.edu.hbvtc.qms.service.IManagementService;
import cn.edu.hbvtc.qms.web.struts.form.CourseEvaluateActionForm;

public class CourseEvaluateAction extends AbstractBaseDispatchAction {

	private IEvaluationService evaluationService = null;
	private IManagementService managementService = null;

	public IEvaluationService getEvaluationService() {
		return evaluationService;
	}

	public void setEvaluationService(IEvaluationService evaluationService) {
		this.evaluationService = evaluationService;
	}

	public IManagementService getManagementService() {
		return managementService;
	}

	public void setManagementService(IManagementService managementService) {
		this.managementService = managementService;
	}

	public ActionForward evaluate(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Course course = managementService.findCourseById(Integer
				.parseInt(request.getParameter("courseId")));
		Student student = managementService.findStudentById(Integer
				.parseInt(request.getParameter("studentId")));
		Teacher teacher = managementService.findTeacherById(Integer
				.parseInt(request.getParameter("teacherId")));

		request.setAttribute("course", course);
		request.setAttribute("student", student);
		request.setAttribute("teacher", teacher);

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String time = sdf.format(new Date());
		request.setAttribute("time", time);

		Criteria criteria = evaluationService.findCriteriaByPurposeAndEnabled("课程质量管理");
		request.setAttribute("criteria", criteria);

		List<Category> categoryList = evaluationService.findCategorysOfCriteria(criteria);
		request.setAttribute("categoryList", categoryList);

		List<Item> itemListAll = new ArrayList<Item>();
		for (Iterator<Category> categoryIter = categoryList.iterator(); categoryIter.hasNext();) {
			Category category = categoryIter.next();
			List<Item> itemList = evaluationService.findItemsOfCategory(category);
			itemListAll.addAll(itemList);
		}
		request.setAttribute("itemList", itemListAll);

		return mapping.findForward("courseEvaluate");
	}

	public ActionForward evaluateSave(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		CourseEvaluateActionForm ceaf = (CourseEvaluateActionForm) form;
		Evaluation evaluation = new Evaluation();
		
		//获得学生所在部门
		User user = managementService.findUserByUsername(this.getPrincipal().getUsername());
		Student stu = managementService.findStudentById(user.getId());
		Department dept = stu.getClazz().getMajor().getDept();
		
		//获得该部门在本学期的最新评价时间段
		EvalPeriod ep = evaluationService.findLateEvalPeriodByDepartmentInThisTerm(dept, managementService.findTermOfNow());
		
		//如果院系管理员当前并未设置课程评价时间，则提示错误消息
		if (ep == null) {
			request.setAttribute("EvalTimeNotSet", "课程评价时间未设置，请联系院系管理员！");
			return mapping.findForward("courseEvaluate");
		}
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String time = sdf.format(new Date());
		
		/*
		 * 如果学生当前登录系统的时间不在课程评价时间段内，则给出不能进行评价的提示信息；
		 * 否则，学生在当前评价时间段内，只能允许评价一次。
		 */
		if (time.compareTo(ep.getStartDate()) < 0 || time.compareTo(ep.getEndDate()) > 0) {
			request.setAttribute("EvalTimeError", "课程评价功能当前时间并未开放，请等待！");
			return mapping.findForward("courseEvaluate");
		} else {
			ClazzArrangement ca = new ClazzArrangement();
			ca.setClazz(managementService.findClazzById(ceaf.getClazzId()));
			ca.setCourse(managementService.findCourseById(ceaf.getCourseId()));
			ca.setTeacher(managementService.findTeacherById(ceaf.getEvaluatedId()));
			
			if (evaluationService.findEvaluationByEvaluator(user, ca, ep) != null) {
				request.setAttribute("EvalExistError", "当前课程评价时间内，只能对该教师所任课程评价一次！");
				return mapping.findForward("courseEvaluate");
			}
		}
		
		int[] itemScore = new int[20];
		itemScore[0] = ceaf.getItem1Score();
		itemScore[1] = ceaf.getItem2Score();
		itemScore[2] = ceaf.getItem3Score();
		itemScore[3] = ceaf.getItem4Score();
		itemScore[4] = ceaf.getItem5Score();
		itemScore[5] = ceaf.getItem6Score();
		itemScore[6] = ceaf.getItem7Score();
		itemScore[7] = ceaf.getItem8Score();
		itemScore[8] = ceaf.getItem9Score();
		itemScore[9] = ceaf.getItem10Score();
		itemScore[10] = ceaf.getItem11Score();
		itemScore[11] = ceaf.getItem12Score();
		itemScore[12] = ceaf.getItem13Score();
		itemScore[13] = ceaf.getItem14Score();
		itemScore[14] = ceaf.getItem15Score();
		itemScore[15] = ceaf.getItem16Score();
		itemScore[16] = ceaf.getItem17Score();
		itemScore[17] = ceaf.getItem18Score();
		itemScore[18] = ceaf.getItem19Score();
		itemScore[19] = ceaf.getItem20Score();

		//表单校验，确保学生选择了20个评分项，并且提交了教学建议
		for (int i = 0; i < itemScore.length; i++) {
			if (itemScore[i] == 0) {
				request.setAttribute("FormRadioSelectError", "请您对所有的评价项目进行评分！");
				return mapping.findForward("courseEvaluate");
			}
		}
		
		if (ceaf.getSuggestion() == null || "".equals(ceaf.getSuggestion())) {
			request.setAttribute("FormSuggestionInputError", "请您对该课程的教学质量提出宝贵意见和建议！");
			return mapping.findForward("courseEvaluate");
		}
		
		evaluation.setEvaluator(managementService.findUserById(ceaf.getEvaluatorId()));
		evaluation.setEvaluated(managementService.findUserById(ceaf.getEvaluatedId()));
		evaluation.setCourse(managementService.findCourseById(ceaf.getCourseId()));
		evaluation.setClazz(managementService.findClazzById(ceaf.getClazzId()));
		evaluation.setTerm(managementService.findTermOfNow());//设置当前学期
		evaluation.setEvalPeriod(ep);//设置当前评价时间段
		
		Criteria criteria = evaluationService.findCriteriaById(ceaf.getCriteriaId());
		evaluation.setCriteria(criteria);
		evaluation.setSuggestion(ceaf.getSuggestion());

		evaluation.setEvaldate(time);
		
		StringBuffer allItemScore = new StringBuffer();
		
		List<Item> allItemList = new ArrayList<Item>();
		Set<Category> categories = criteria.getCategories();
		for (Iterator<Category> iter = categories.iterator(); iter.hasNext();) {
			Set<Item> items = iter.next().getItems();
			allItemList.addAll(items);
		}
		
		double totalScore = 0;
		for (int i = 0; i < itemScore.length; i++) {
			double score = itemScore[i] * allItemList.get(i).getProportion();
			allItemScore.append(score);
			if (i < itemScore.length - 1) {
				allItemScore.append(",");
			}
			totalScore += score;
		}

		evaluation.setScore(allItemScore.toString());//保存每个评价指标的得分情况
		evaluation.setTotalScore(String.valueOf(totalScore));//保存评价总得分
		
		evaluationService.saveEvaluation(evaluation);
		
		return mapping.findForward("courseEvaluateSave");
	}
}
